package com.itbour.web.action.com;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.itbour.common.base.BaseAction;
import com.itbour.common.log.ErrorLogger;
import com.itbour.common.util.StringUtils;
import com.itbour.def.MessageCode;
import com.itbour.def.MessageCodeConstants;
import com.itbour.def.MessageType;
import com.itbour.def.SystemConf;
import com.itbour.dto.com.UserInfoDto;
import com.opensymphony.xwork2.ActionContext;

/**
 * copyright pirate alliance team 2014
 *
 * @author lunxing
 */

public class FileUploadAction extends BaseAction {
	private File file;           //文件
	private File fontFile;		 //字体文件
    private String fileFileName; //文件名   
    private String fontFileName; //字体文件名
    private String filePath;     //文件路径  
    private InputStream inputStream;  
    private String mp3;
  
    private String userId;
    private String goodsClass;
    
    public String getMp3() {
		return mp3;
	}

	public void setMp3(String mp3) {
		this.mp3 = mp3;
	}

	/** 
     * 图片上传 
     *  
     * @return 
     */  
    public void fileUpload() {  
        //String path = ServletActionContext.getServletContext().getRealPath("/upload");  
    	String suf = ".jpg";
    	String path = SystemConf.getImageRootDir();
  		if(StringUtils.isNotEmpty(mp3)){
  			suf = ".mp3";
  			path = SystemConf.getSoundRootDir();
  			
  		}
  		String newPath = StringUtils.linkFilePath(path, goodsClass);
  		File file = new File(newPath); // 判断文件夹是否存在,如果不存在则创建文件夹  
        if (!file.exists()) {  
            file.mkdir();  
        }  
        try {  
          if (this.file != null) {  
      		Date date = new Date();
      		//DateFormat df1 = new SimpleDateFormat("yyyyMMdd");
      		DateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmssSSS");
      		
      		String tmpImagePath = df2.format(date) + StringUtils.getFixLenthString(4) + suf;
        
      		String fileUrl = StringUtils.linkFilePath(newPath, tmpImagePath);
      		File saveFile = new File(fileUrl);

      		if(this.getFile() == null)
      		{
      			return;
      		}
      
      		FileUtils.copyFile(this.getFile(), saveFile);
      		filePath = fileUrl;
      		if(StringUtils.isNotEmpty(mp3)){
      			writeText(SystemConf.getSoundServerUrl() + goodsClass + "/" + tmpImagePath);
      		}else{
      			writeText(SystemConf.getImageServerUrl() + goodsClass + "/" + tmpImagePath);
      		}
          }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        //return SUCCESS;  
    }  

    // 上传字体文件
    public void fileUpload2() {  
    	Map<String, Object> session = ActionContext.getContext()
				.getSession();
    	UserInfoDto user = (UserInfoDto)session.get("user");
    	if (StringUtils.isBlank(userId)) {
    		userId = String.valueOf(user.getUser_id());
    	}
    	
    	String tmpSubPath = "tmp";
		if (!StringUtils.isBlank(userId)) {
			tmpSubPath = userId.trim();
		}
		
		String path = SystemConf.getFontRootDir();
		String newPath = StringUtils.linkFilePath(path, tmpSubPath);
		
		File tmpFile = new File(newPath); // 判断文件夹是否存在,如果不存在则创建文件夹  
        if (!tmpFile.exists()) {  
        	tmpFile.mkdir();  
        }  
        try {
          if (this.getFontFile() != null) {
      		
      		String fileNm = fontFileName;
        
      		String fileUrl = StringUtils.linkFilePath(newPath, fileNm);
      		File saveFile = new File(fileUrl);
      		if(this.getFontFile() == null) {
      			return;
      		}
      
      		FileUtils.copyFile(this.getFontFile(), saveFile);
      		filePath = fileUrl;
      		//writeText(fileUrl);
      		HashMap<String, Object> resMap = new HashMap<String, Object>();
      		resMap.put("status", true);
      		resMap.put("fileName", fileNm);
      		resMap.put("savePath", fileUrl);
      		writeJSON(resMap);
          }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }
        //return SUCCESS;  
    }

    /** 
     * 用于图片页面显示 
     *  
     * @return 
     */  
    public String readImg() {  
        try {  
            inputStream = new FileInputStream(new File(getRequest().getParameter("path")));  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        }  
        return SUCCESS;  
    }  
    /** 
     * 图片下载 
     * @return 
     */  
    public String download() {  
        String path = filePath;  
        HttpServletResponse response = ServletActionContext.getResponse();  
        try {  
            // path是指欲下载的文件的路径。  
            File file = new File(path);  
            // 取得文件名。  
            String filename = file.getName();  
            // 取得文件的后缀名。  
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();  
            // 以流的形式下载文件。  
            InputStream fis = new BufferedInputStream(new FileInputStream(path));  
            byte[] buffer = new byte[fis.available()];  
            fis.read(buffer);  
            fis.close();  
            //清空response  
            response.reset();  
            //设置response的Header  
            String filenameString = new String(filename.getBytes("gbk"),"iso-8859-1");  
            response.addHeader("Content-Disposition", "attachment;filename=" + filenameString);  
            response.addHeader("Content-Length", "" + file.length());  
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());  
            response.setContentType("application/octet-stream");  
            toClient.write(buffer);  
            toClient.flush();  
            toClient.close();  
        } catch (IOException ex) {  
            ex.printStackTrace();  
        }  
        return null;  
    }  
  
    public File getFile() {  
        return file;  
    }  
  
    public void setFile(File file) {  
        this.file = file;  
    }  
  
    public String getFileFileName() {  
        return fileFileName;  
    }  
  
    public void setFileFileName(String fileFileName) {  
        this.fileFileName = fileFileName;  
    }  
  
    public String getFontFileName() {
		return fontFileName;
	}

	public void setFontFileName(String fontFileName) {
		this.fontFileName = fontFileName;
	}

	public String getFilePath() {  
        return filePath;  
    }  
  
    public void setFilePath(String filePath) {  
        this.filePath = filePath;  
    }  
  
    public InputStream getInputStream() {  
        return inputStream;  
    }  
  
    public void setInputStream(InputStream inputStream) {  
        this.inputStream = inputStream;  
    }  
  
    private static final long serialVersionUID = 1L;

	public String getGoodsClass() {
		return goodsClass;
	}

	public void setGoodsClass(String goodsClass) {
		this.goodsClass = goodsClass;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public File getFontFile() {
		return fontFile;
	}

	public void setFontFile(File fontFile) {
		this.fontFile = fontFile;
	}
	
}
